import io from 'socket.io-client';

import { Port, resetStore, setHubInfo, setSocketId } from 'store';

import { getIoUrl, getIoOptions } from './utils';
import { incomingParser } from 'incomingParser';
import {
  CIRCULAR_GET_DATA_CH2,
  CIRCULAR_GET_DATA_CH3,
  CIRCULAR_GET_SERIAL_CH2,
  CIRCULAR_GET_SERIAL_CH3,
} from 'constatnts';

const socket = io(getIoUrl(), getIoOptions());
socket.off();

export const sendData = (numbers: number[]) => {
  socket.emit('sendData', numbers);
};

export const sendCircularGetSerialCh2 = () => {
  sendData(CIRCULAR_GET_SERIAL_CH2);
};

export const sendCircularGetSerialCh3 = () => {
  sendData(CIRCULAR_GET_SERIAL_CH3);
};

export const sendCircularGetDataCh2 = () => {
  sendData(CIRCULAR_GET_DATA_CH2);
};

export const sendCircularGetDataCh3 = () => {
  sendData(CIRCULAR_GET_DATA_CH3);
};

export const subscribeSocket = () => {
  socket.on("connect", () => {
    setSocketId(socket.id || null);

    const engine = socket.io.engine;
    console.log('engine.transport.name', engine.transport.name); // in most cases, prints "polling"
  
    engine.once("upgrade", () => {
      // called when the transport is upgraded (i.e. from HTTP long-polling to WebSocket)
      console.log('engine.transport.upgrade', engine.transport.name); // in most cases, prints "websocket"
    });
    
    const message = socket.recovered ? 'Канал восстановлен' : `Канал подключен. id: ${socket.id}`;
    console.log(message);

    socket.emit('getHubInfo');
  });

  socket.on('disconnect', (reason) => {
    setSocketId(null);

    console.log(`Потеря канала. Причина: ${reason}`);
  
    if (reason === 'io server disconnect') {
      console.log('Повторное подключение...');
      // the disconnection was initiated by the server, you need to reconnect manually
      socket.connect();
    }
    // else the socket will automatically try to reconnect
    resetStore();
  });

  socket.on('setHubInfo', (hubInfo: Port | null) => {
    setHubInfo(hubInfo);
  });

  socket.on('data', (data: number[]) => {
    incomingParser(data);
  });

  socket.on('error', (error: string) => {
    console.error('Error', error);
  });

  socket.connect();
};

export const unSubscribeSocket = () => {
  socket.off();
};

export default socket;
